package com.homelock.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.homelock.common.enumeration.NotifyTypeEnum;
import com.homelock.common.util.HttpClientHelper;
import com.homelock.dto.IOTResp;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.HashMap;

/**
 * 消息注册接口
 * @author zoumy
 * @CreateDate 20190920
 *
 */
@Component
public class RecordSuscribeRunner implements ApplicationRunner {

    private static final Logger logger = LoggerFactory.getLogger(RecordSuscribeRunner.class);

    @Autowired
    private HttpClientHelper httpClientHelper;
    /**
     * IOT服务IP
     */
    @Value("${iot.server.ip}")
    private String ip;
    /**
     * IOT服务端口
     */
    @Value("${iot.server.port}")
    private String port;
    /**
     * IOT 注册接口地址
     */
    @Value("${iot.server.request.suscribe}")
    private String suscribeRequest;

    @Value("${iot.callback.url}")
    private String susParamCallBackUrl;
    @Value("${server.http.port}")
    private String serverHttpPort;
    @Value("${server.port}")
    private String serverHttpsPort;
    @Value(("${iot.server.partnercode}"))
    private String partnerCode;
    @Value("${iot.server.request.suscribe.off}")
    private boolean offState;


    private static final String APPEND_SYM = ":";


    /**
     * 参数
     */
    private static final String SUS_PARAM_PARTNERCODE = "partnerCode";
    private static final String SUS_PARAM_REMOTEURI = "remoteUri";
    private static final String SUS_PARAM_NOTIFYTYPE = "notifyType";

    @Override
    public void run(ApplicationArguments args) throws Exception {
        logger.info("消息注册接口关闭状态："+offState);
        if(!offState){
            logger.info("消息注册接口启动");
            requestForSubcribe();
        }
    }

    private IOTResp requestForSubcribe(){
        IOTResp resp = null;
        try {
            String result = httpClientHelper.post(querySuscribeUrl(), queryParams(), null);
            logger.info("注册接口返回：" + result);
            if (StringUtils.isNotEmpty(result)) {
                // 接口失败则去掉转义字符以及前后双引号
                 result = StringEscapeUtils.unescapeJava(result);
                 if(result.startsWith("\"") && result.endsWith("\"")) {
                     result = result.substring(1, result.length() - 1);
                 }
                logger.info("转义之后的返回结果：" + result);
                resp = new ObjectMapper().readValue(result, IOTResp.class);
                if(resp.getStatus() == IOTResp.SUCCESS){
                    logger.info("注册成功："+result);
                }else{
                    logger.info("注册失败："+result);
                }
            }else{
                logger.info("注册失败,返回值为空");
            }
        }catch (Exception e){
            logger.error(e.getMessage());
            e.printStackTrace();
        }
        return resp;
    }

    /**
     * 获取注册接口
     * @return
     */
    private  String querySuscribeUrl(){
        String suscribeUrl = new StringBuffer(ip).append(APPEND_SYM).append(port).append(suscribeRequest).toString();
        logger.info("注册的请求接口："+suscribeUrl);
        return suscribeUrl;
    }

    private HashMap<String,Object> queryParams(){
        HashMap<String,Object> params = new HashMap<>();
        params.put(SUS_PARAM_PARTNERCODE,partnerCode);  // partnercode参数
        params.put(SUS_PARAM_REMOTEURI,susParamCallBackUrl);  // 回调接口参数
        params.put(SUS_PARAM_NOTIFYTYPE, NotifyTypeEnum.POST.getCode());  // 接口请求类型：post
        return params;
    }

}
